package com.iris.live.services.services.impl;

import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.common.JsonObjectUtils;
import com.iris.live.services.common.reconsitution.DefaultValueConstant;
import com.iris.live.services.data.models.*;
import com.iris.live.services.data.repositories.*;
import com.iris.live.services.models.PageData;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.services.RoleItemInfoService;
import com.iris.live.services.services.RoleService;
import com.iris.live.services.services.SystemService;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionInterceptor;
import org.springframework.util.Assert;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *
 */
@Service
@Transactional//(readOnly = true)
public class SystemServiceImpl implements SystemService {
    private static org.slf4j.Logger logger = LoggerFactory.getLogger(SystemServiceImpl.class);

    @Autowired
    private Lsh消息Repository lsh消息Repository;

    @Autowired
    private SystemRepository systemRepository;

    @Autowired
    private MessageSettingRepository messageSettingRepository;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;
    //初始化报价单流水
    @Autowired
    private OrderFlowingwaterRepository orderFlowingwaterRepository;
    //初始化订单流水
    @Autowired
    private QuotationFlowingwaterRepository quotationFlowingwaterRepository;
    //保险手续费
    @Autowired
    private Lsh保险手续费Repository lsh保险手续费Repository;
    //保险公式设置
    @Autowired
    private Lsh保险公司设置Repository lsh保险公司设置Repository;
    //保险公司使用
    @Autowired
    private Lsh保险公司使用Repository lsh保险公司使用Repository;
    //保险战败原因附属
    @Autowired
    private Lsh保险战败原因Repository lsh保险战败原因Repository;
    @Autowired
    private Lsh保险战败原因附属Repository lsh保险战败原因附属Repository;
    //金融战败原因附属
    @Autowired
    private Lsh金融战败原因Repository lsh金融战败原因Repository;
    @Autowired
    private Lsh金融战败原因附属Repository lsh金融战败原因附属Repository;
    @Autowired
    private 用户Repository userRepository;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleItemSqlRepository roleItemSqlRepository;


    @Override
    @Transactional
    public Lsh消息Model saveMessage(Lsh消息Model model) {
        Assert.notNull(model);
        return this.lsh消息Repository.save(model);
    }

    @Override
    @Transactional
    public boolean delMessage(int id, String username) {
        int result = this.lsh消息Repository.delBy消息编号(id, username);
        return true;
    }

    @Override
    public PageData getMessageList(GetMessageListRequest request, String permit) {
        return this.systemRepository.getMessageList(request.getPageSize(), request.getPageIndex(), request.receiver,
                request.sender, request.updateDate, request.content, request.remark, permit);
    }


    @Override
    public ResultData getMessageListModelAndIsDelete(String username, String permit) {
        return this.systemRepository.getMessageListModelAndIsDelete(username, permit);
    }

    @Override
    public List saveMessageListModelAndIsDelete(int ids) {
        List newmodel1 = new ArrayList();

        try {

            Lsh消息Model newmodel = lsh消息Repository.findOne(ids);
            newmodel.set是否删除("是");
            Lsh消息Model nede = lsh消息Repository.save(newmodel);
            newmodel1.add(nede);
        } catch (Exception e) {
            TransactionInterceptor.currentTransactionStatus().setRollbackOnly();
            logger.error("系统异常。", e);
        }
        return newmodel1;
    }


    @Override
    public List getMessageSettingList(String permit, String type) {
        return this.systemRepository.getMessageSettingList(permit, type);
    }

    @Override
    public boolean saveMessageSetting(MessageSettingModel model) {
        logger.info("saveMessageSetting参数为:" + JsonObjectUtils.writeAsJson(model));
        try {
            //查看是否已经存在
//            MessageSettingModel modelOld = messageSettingRepository.findByPermitAndType(model.getPermit(),model.getType(),"1");
//            if (null != modelOld){
//                return false;
//            }
            this.messageSettingRepository.save(model);
            return true;
        } catch (Exception e) {
            logger.error("saveMessageSetting保存异常。", e);
            return false;
        }
    }

    @Override
    public ResultData roleLoginByClientType(String username, String permit, Integer clientType) {
        switch (clientType){
            case DefaultValueConstant.PLATFORM_PC_GROUP :
                return roleLoginByPcGroup(username,permit);
            case DefaultValueConstant.PLATFORM_PC_DEALER :
                return new ResultData("true","可以登录");
        }
        return new ResultData("true","可以登录");
    }

    @Override
    public ResultData getUserFunctionByRole(String username, String permit) {
        //查询用户的所属角色
        用户Model user = userRepository.findByYonghumingUserName(permit,username);
        if(null ==user){
            return new ResultData("false","当前用户不存在");
        }
        //查询角色ID
        RoleModel role = roleService.getRoleInfo(user.get角色());
        if(null ==user){
            return new ResultData("false","当前角色不存在");
        }
        //中间表中取得角色对应的权限集合
        List list = roleItemSqlRepository.getFunctionListByRoleId(Integer.parseInt(role.getRoleId()));
        return new ResultData("true","ok",new PageData(list,1));
    }

    private ResultData roleLoginByPcGroup(String username, String permit){
        //查询用户角色
        用户Model user = userRepository.findByYonghumingUserName(permit,username);
        if(null ==user && !"Admin".equals(username)){
            return new ResultData("false","当前用户不存在");
        }
        //查询集团中是否有当前用户角色
        RoleModel role = roleService.getRoleExists(0,user.get角色());
        if( null == role ){
            return new ResultData("false","当前用户为" + user.get角色() +",无权登录PC集团端");
        }
        return new ResultData("true",user.get角色());

    }

    //------------------------------------------------初始化模块start------------------------------------------------------
    @Override
    public ResultData initPermitData(String permit){
        //取得经销商表中是否第一个许可（如果是先走设置全局再走许可相关数据 否则只走许可相关数据）
        int isFirstPermit = 0;
        List<Lsh经销商表Model> list =  lsh经销商表Repository.findAllPermit();
        if (null != list && list.size() ==1 && permit.equals(list.get(0).getBmbs())){
            isFirstPermit = 1;
        }
        switch (isFirstPermit){
            case 0:
                initLocalData(permit);
                break;
            case 1:
                initOverallSituationData(permit);
                initLocalData(permit);
                break;
        }
        return null;
    }

    /**
     * 全局相关数据
     * @return
     */
    private  ResultData  initOverallSituationData(String permit){
        //初始化虚拟车架号（virtual_stock）
        //初始化保险战败原因
        //初始化金融战败原因
        //保有车型相关数据
        //保险公司设置
        //销售项目设置
        //精品NC分类
        //精品分类
        //精品种类
        //si_setting
        //保险险种
        //市场设置
        //活动类型
        //car_sales_state
        //付款款项
        //角色表
        return  null;
    }

    /**
     * 许可相关数据
     * @return
     */
    @Transactional
    private  ResultData  initLocalData(String permit){
        //查询保险公司集合
        List<Lsh保险公司设置Model> companyList = lsh保险公司设置Repository.findAllCompanyByEnable();
        //查询保险战败原因集合
        List<Lsh保险战败原因Model> insuranceReasonList = lsh保险战败原因Repository.findListByPermit(permit);
        //查询金融战败原因集合
        List<Lsh金融战败原因Model> financeReasonList = lsh金融战败原因Repository.findListByPermit(permit);
        //初始化报价单流水
        quotationFlowingwaterRepository.save(new QuotationFlowingwaterModel(1,permit,new Date()));
        //初始化订单流水
        orderFlowingwaterRepository.save(new OrderFlowingwaterModel(1,permit,new Date()));
        //保险公司使用
        initInsuranceCompanyUse(companyList,permit);
        //初始化保险手续费
        initInsuranceCounterFee(companyList,permit);
        //保险战败原因附属(稳定起见从字典表获取长度迭代初始化)
        initInsuranceReason(insuranceReasonList);
        //金融战败原因附属(稳定起见从字典表获取长度迭代初始化)
        initFinanceReason(financeReasonList);
        return  new ResultData("true","当前许可" + permit +",初始化数据成功");
    }

    /**
     * 保险公司使用
     * @param permit
     * @param companyList
     * @throws Exception
     */
    private void initInsuranceCompanyUse( List<Lsh保险公司设置Model> companyList,String permit){
        //从保险公司字典表获取长度迭代
        for (Lsh保险公司设置Model model:companyList) {
            lsh保险公司使用Repository.save(new Lsh保险公司使用Model(model.get保险公司编号(),permit,Lsh金融战败原因Model.STATUS_STR_ONE,"Admin", DateFormatUtils.getFormatTimestamp(DateFormatUtils.TIME_FORMAT_STR_YYYY_MM_DD_HH_MM_SS,new Date())));
        }
    }

    /**
     * 初始化保险手续费
     * @param permit
     * @param companyList
     * @throws Exception
     */
    private void initInsuranceCounterFee( List<Lsh保险公司设置Model> companyList,String permit){
        //从保险公司字典表获取长度迭代，每个字典元素按客户类型1&2分别初始化
        for (Lsh保险公司设置Model model:companyList) {
            lsh保险手续费Repository.save(new Lsh保险手续费Model(model.get保险公司编号(),permit,null,null,null,Lsh保险手续费Model.CUSTOMER_TYPE_RES_STR_ONE,
                    DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date())));
            lsh保险手续费Repository.save(new Lsh保险手续费Model(model.get保险公司编号(),permit,null,null,null,Lsh保险手续费Model.CUSTOMER_TYPE_RES_STR_TWO,
                    DateFormatUtils.getFormatTimestamp("yyyy-MM-dd HH:mm:ss", new Date())));
        }
    }

    /**
     * 初始化保险战败原因附属
     * @param insuranceReasonList
     * @throws Exception
     */
    private void initInsuranceReason( List<Lsh保险战败原因Model> insuranceReasonList){
        //从字典表获取长度迭代初始化，每个字典元素按保险准战败、保险战败分别初始化
        for (Lsh保险战败原因Model model:insuranceReasonList) {
            lsh保险战败原因附属Repository.save(new Lsh保险战败原因附属Model(model.get新保战败原因编号(),Lsh保险战败原因附属Model.FAIL_CONTENT_RES_STR_ONE,null));
            lsh保险战败原因附属Repository.save(new Lsh保险战败原因附属Model(model.get新保战败原因编号(),Lsh保险战败原因附属Model.FAIL_CONTENT_RES_STR_TWO,null));
        }
    }

    /**
     * 初始化金融战败原因附属
     * @param financeReasonList
     * @throws Exception
     */
    private void initFinanceReason( List<Lsh金融战败原因Model> financeReasonList){
        //从金融战败原因字典表获取长度迭代，每个字典元素按战败分类金融战败&准全款分别初始化
        for (Lsh金融战败原因Model model:financeReasonList) {
            lsh金融战败原因附属Repository.save(new Lsh金融战败原因附属Model(model.get金融战败原因编号(),Lsh金融战败原因Model.FAIL_CONTENT_RES_STR_ONE,null));
            lsh金融战败原因附属Repository.save(new Lsh金融战败原因附属Model(model.get金融战败原因编号(),Lsh金融战败原因Model.FAIL_CONTENT_RES_STR_TWO,null));
        }
    }

    @Override
    public ResultData getVirusKillList() {
        List<VirusKillerModel> models = this.systemRepository.getVirusKillerList();

        ResultData rd = new ResultData();
        if(models != null) {
            rd.setPageData(new PageData(models, models.size()));
        }

        return rd;
    }
}
